<template>
  <div>
    <card-table style="height: calc(100vh - 100px)">
      <div class="card-table-header">
        <div class="card-table-header-btns">
          <el-button
            v-if="hasPermission('system:item:add')"
            class="btn-search"
            size="small"
            icon="el-icon-plus"
            @click="handleClick(null, 'add')"
            >新增</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:item:remove')"
            class="btn-search"
            size="small"
            icon="el-icon-delete"
            :disabled="btnDisabled"
            @click="handleClick(null, 'delete')"
            >删除</el-button
          >
          <el-button
            v-if="isSuperAdmin || hasPermission('system:item:export')"
            class="btn-search"
            size="small"
            icon="el-icon-upload2"
            @click="handleClick(null, 'export')"
            >导出</el-button
          >

          <el-input
            v-if="isSuperAdmin || hasPermission('system:item:list')"
            v-model="input"
            placeholder="请输入项目名称/ 项目地址/ 项目简介/ 管理员/ 备注信息"
            style="width: 450px; margin-left: 10px"
            clearable
            size="small"
            @change="initTable"
          >
            <el-button slot="append" icon="el-icon-search" @click="initTable"></el-button>
          </el-input>
        </div>
        <div class="card-table-header-actions">
          <table-action
            :table-header="tableHeader"
            :eye-show="false"
            :search-show="false"
            @check-change="handleCheckChange"
            @search-click="handleSearchClick"
            @init-click="handleInitClick"
          />
        </div>
      </div>
      <el-table
        v-loading="loading"
        :key="tableKey"
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        :header-cell-style="{ background: '#eff3f8', color: '#333' }"
        size="small"
        stripe
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        highlight-selection-row
        border
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          v-for="item in tableHeader"
          v-if="item.visible"
          :key="item.prop"
          :label="item.title"
          :min-width="item.width"
          :prop="item.prop"
          :show-overflow-tooltip="true"
          :align="item.align"
          sortable
        >
          <template #default="scope">
            <span
              v-if="item.prop === 'itemName'"
              class="link-type"
              @click="handleClick(scope.row, 'itemName')"
              ><svg-icon
                icon-class="table-link"
                style="margin-right: 5px; width: 14px; height: 14px; fill: #165eff"
              />{{ scope.row.itemName }}</span
            >

            <span
              v-else-if="item.prop === 'itemManager'"
              class="link-type"
              @click="handleClick(scope.row, 'itemManager')"
            >
              <svg-icon
                icon-class="table-set"
                style="margin-right: 5px; width: 15px; height: 15px; fill: #165eff"
              ></svg-icon
              >{{ scope.row.itemManager || "未指定" }}</span
            >
            <span
              v-else-if="item.prop === 'itemOperator'"
              class="link-type"
              @click="handleClick(scope.row, 'itemOperator')"
            >
              <svg-icon
                icon-class="table-set"
                style="margin-right: 5px; width: 15px; height: 15px; fill: #165eff"
              />{{ scope.row.itemOperator || "未指定" }}
            </span>
            <span v-else>
              {{ scope.row[item.prop] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="hasPermission('system:item:edit')"
          label="操作"
          size="small"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="handleClick(scope.row, 'edit')"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <XyPagination
        :total="total"
        :pageSize="pageSize"
        :pageNum="currentPage"
        @pagination="handlerPagination"
      ></XyPagination>
    </card-table>
    <DialogAdmin v-model="dialogAdminVisible" :field="field" @close="handleDialogClose" />
    <DialogDeitail
      v-model="dialogDetailVisible"
      :field="field"
      :rowData="rowData"
      @close="handleDialogDetailClose"
      @init="initTable"
    />
  </div>
</template>
<script>
import CardSearch from "@/components/CardSearch";
import CardTable from "@/components/CardTable";
import TableAction from "@/components/TableAction";
import DialogAdmin from "./component/DialogAdmin.vue";
import DialogDeitail from "./component/DialogDetail.vue";
import XyPagination from "@/components/XyPagination";
import { hasPermission, isSuperAdmin } from "@/utils/hasBtnPermission";
import { projectList, projectExport, projectDelete } from "@/api/projectmanagement";
export default {
  name: "ProjectList",
  components: {
    CardSearch,
    CardTable,
    DialogAdmin,
    TableAction,
    DialogDeitail,
    XyPagination,
  },
  data() {
    return {
      tableKey: 0, // 用于强制刷新表格
      searchCardShow: true,
      input: "",
      tableHeader: [
        {
          title: "项目名称",
          prop: "itemName",
          width: "200",
          visible: true,
          align: "left",
        },
        {
          title: "项目管理员",
          prop: "itemManager",
          width: "150",
          visible: true,
          align: "left",
        },
        {
          title: "所属企业",
          prop: "deptName",
          width: "150",
          visible: true,
          align: "left",
        },
        {
          title: "设备总数",
          prop: "devTotalNumbers",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "在线数量",
          prop: "devOnlineNumbers",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "离线数量",
          prop: "devOfflineNumbers",
          width: "120",
          visible: true,
          align: "center",
        },
        {
          title: "项目调试员",
          prop: "itemOperator",
          width: "120",
          visible: true,
          align: "left",
        },
        {
          title: "项目地址",
          prop: "itemAdress",
          width: "250",
          visible: true,
          align: "left",
        },
        {
          title: "创建时间",
          prop: "createTime",
          width: "150",
          visible: true,
          align: "center",
        },
      ],
      tableData: [],
      multipleSelection: [],
      btnDisabled: true,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      dialogAdminVisible: false,
      dialogDetailVisible: false,
      field: "",
      tableHeight: 550,
      rowData: {},
      loading: false,
    };
  },
  computed: {
    isSuperAdmin() {
      return isSuperAdmin();
    },
  },
  mounted() {
    this.calculateTableHeight();
    this.initPage();
  },
  methods: {
    // 新增初始化页面方法
    initPage() {
      const userIdFromUrl = this.$route.query.userId;

      if (userIdFromUrl) {
        this.loading = true;
        // 如果有userId参数，先获取用户信息，再查询表格数据
        this.getUserInfo(userIdFromUrl)
          .then(() => {
            this.loading = false;
            this.initTable();
          })
          .catch((error) => {
            this.$message.error(error.msg); // 即使获取用户信息失败也尝试查询表格数据
          });
      } else {
        // 如果没有userId参数，直接查询表格数据
        this.initTable();
      }
    },
    getUserInfo(userId) {
      return new Promise((resolve, reject) => {
        try {
          // 使用回调方式确保能捕获到结果
          this.$store
            .dispatch("user/getInfo", userId)
            .then((response) => {
              resolve(response);
            })
            .catch((error) => {
              reject(error);
            });
        } catch (error) {
          reject(error);
        }
      });
    },
    initTable() {
      let data = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        searchValue: this.input,
      };
      projectList(data).then((res) => {
        if (res.code == 0) {
          this.tableData = res.rows;
          this.total = res.total;
        }
      });
    },
    handlerPagination(page) {
      this.currentPage = page.pageNum;
      this.pageSize = page.pageSize;
      this.initTable();
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length > 0) {
        this.btnDisabled = false;
      } else {
        this.btnDisabled = true;
      }
      console.log(this.multipleSelection);
    },
    handleClick(row, field) {
      switch (field) {
        case "itemName":
          let url = window.location.origin;
          window.open(
            `${url}/#/DeviceManagement/DeviceList?userId=` + row.itemManagerUserId,
            "_blank"
          );
          break;
        case "itemManager":
          this.dialogAdminVisible = true;
          this.field = "projectAdmin";
          break;
        case "itemOperator":
          this.dialogAdminVisible = true;
          this.field = "personInCharge";
          break;
        case "add":
          this.dialogDetailVisible = true;
          this.field = "add";
          this.rowData = { deptName: this.tableData[0].deptName };
          break;
        case "edit":
          this.dialogDetailVisible = true;
          this.rowData = row;
          break;
        case "delete":
          this.$confirm(
            `确认删除选中的${this.multipleSelection.length}个项目吗?`,
            "系统提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            let ids = this.multipleSelection.map((item) => item.id);
            projectDelete({ ids }).then((res) => {
              if (res.code == 0) {
                this.initTable();
              } else {
                this.$message.error(res.msg);
              }
            });
          });
          break;
        case "export":
          let data = {
            searchValue: this.input,
          };
          projectExport(data).then((res) => {
            if (res.code == 0) {
              window.open(res.data.downLoadUrl, "_self");
            } else {
              this.$message({
                type: "error",
                message: res.msg,
              });
            }
          });
        default:
          break;
      }
    },
    // 处理表头显示隐藏
    handleCheckChange(checkedValues) {
      this.tableHeader.forEach((item) => {
        item.visible = checkedValues.includes(item.prop);
      });
      this.tableKey += 1;
    },
    handleSearchClick() {
      this.searchCardShow = !this.searchCardShow;
    },
    handleInitClick() {
      this.initTable();
    },
    handleDialogClose() {
      this.field = "";
      this.dialogAdminVisible = false;
    },
    handleDialogDetailClose() {
      this.field = "";
      this.dialogDetailVisible = false;
    },
    hasPermission(permission) {
      return hasPermission(permission);
    },
    calculateTableHeight() {
      // 根据容器实际高度计算表格高度
      this.$nextTick(() => {
        const container = this.$refs.multipleTable.$el?.parentElement;
        if (container) {
          // 减去表头和其他元素的高度
          this.tableHeight = container.clientHeight - 120; // 120为估计的其他元素高度
        }
      });
    },
  },
};
</script>
